/**
 * 业务表单基础的增、改
 */
import {getDetail, getFormBuildConfig, add, update, init,dealMksApi} from '@/views/youshuda/api/BaseApi'
//表单配置
import {
  formConf
} from '@/views/youshuda/components/FormBuild/generator/config'
import request from "@/utils/request";
import {strIsNotEmpty,escapeDeal} from "@/views/youshuda/utils/youshuda";
import {EventMixins} from "@/views/youshuda/mixins/EventMixins"

export const TableDetailMixins = {
  components: {
    FormItem: () => import('@/views/youshuda/components/FormItem/index'),
    //表单配置展示组件
    DraggableItem: () => import('@/views/youshuda/components/FormBuild/generator/DraggableItem')
  },
  mixins: [EventMixins],
  props: {
    defPk: {
      default: ''
    },
    //处理入口类型：业务表单处理（Form）、流程表单处理（Proc）
    enterType: {
      default: 'Form'
    },
    //当前操作请求URL前缀
    visitConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //表单设计Key
    formBuildKey: {
      default: ''
    },
    //是否需要操作按钮
    needOperBtn: {
      default: true
    },
    //当前表单字段信息
    fieldInfo: {
      type: Array,
      default: []
    },
    //表单配置信息
    configParams: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {},
  data() {
    return {
      // 字段信息
      init: {
        fieldInfo: []
      },
      // 表单参数
      form: {},
      // 标识进入页面是否加载完成
      isLoadFinish: false,
      //表单设计字段配置信息
      formBuildConfig: [],
      formConf,
      // 标识提交按钮是否可用
      isSubmitForm: false,
      //业务模块生成ID
      tabGenId: '',
      //新增还是编辑
      operType: 'add',
      // 主子表时，关联字段
      foreignKey: '',
      //主表数据
      parentFormData: '',
      // 加载图片
      loading: require('@/assets/images/loading.gif'),

      nowRenderKey: '' //重新渲染组件时唯一标识
    }
  },
  created() {
    //业务模块生成ID
    if (this.strIsEmpty(this.tabGenId)) {
      //提交URL前缀
      if (this.visitConfig == null || this.visitConfig == undefined) {
        console.log("数据组件关联模块配置为空，中止加载...");
        return;
      }
      if (this.visitConfig['genType'] == '2') {
        //优树搭
        this.tabGenId = this.visitConfig['tableId']
      } else {
        //平台标准方式
        this.prefixUrl = this.visitConfig['baseUrlPrefix']
      }
    }
    if (!this.strIsNotEmpty(this.tabGenId) && !this.strIsNotEmpty(this.prefixUrl)) {
      this.msgError("操作失败，当前模块请求地址为空")
      return;
    }
    this.loading = this.loading + '?' + Math.random()
    //获取主子表关联字段
    if (this.configParams && this.configParams['PrimaryFormData']) {
      this.foreignKey = this.configParams['foreignKey']
      //主表关联值
      this.parentFormData = this.configParams['PrimaryFormData'][this.configParams['primaryTableKey']]
      //设置关联值
      this.form[this.foreignKey] = this.parentFormData;
    }
    /** 加载数据 **/
    this.initData()
  },
  methods: {
    /** 获取数据 */
    initData() {
      if (this.strIsNotEmpty(this.defPk)) {
        this.operType = 'edit'
      } else {
        this.operType = 'add'
      }
      /**
       * 判断新增/修改
       */
      if (this.operType == 'edit') {
        this.reset()
        getDetail(this.tabGenId, this.prefixUrl, this.defPk).then(res => {
          if (res.code == 200) {
            //表单数据
            this.form = res.data['data']
            //表单设计字段配置信息
            this.formBuildConfig = res.data['formBuildConfig']
            //生成唯一标识，主要考虑用于子表
            if (this.strIsEmpty(this.form['defPk'])) {
              this.form['defPk'] = this.generateUuid()
            }
            this.resetForm('form')
            // 切换加载效果
            this.closeLoad()
          } else {
            this.msgError(res.msg)
          }
        })
      } else {
        //获取表单设计配置信息
        getFormBuildConfig(this.formBuildKey).then(res => {
          if (res.code == 200) {
            //表单重置
            this.reset()
            //表单设计字段配置信息
            this.formBuildConfig = res.data
            // 切换加载效果
            this.closeLoad()
          } else {
            this.msgError(res.msg)
          }
        })
      }
    },
    closeLoad() {
      var that = this
      // 标记页面已加载完成
      setTimeout(function () {
        that.isLoadFinish = true
      }, 800)
    },
    // 表单重置
    reset() {
      this.init.fieldInfo = JSON.parse(JSON.stringify(this.fieldInfo))
      for(let field of this.init.fieldInfo){
        if(this.strIsNotEmpty(field.columnName)){
          this.$set(field, 'fieldData', null)
            // 表单数据置空
          this.$set(this.form, field.columnName, null)
        }
      }
      //设置关联值
      this.form[this.foreignKey] = this.parentFormData;
      //生成唯一标识，主要考虑用于子表
      if (this.strIsEmpty(this.form['defPk'])) {
        this.form['defPk'] = this.generateUuid()
      }
      this.resetForm('form')
    },
    /** 取消按钮 */
    cancel() {
      this.$emit('cancel')
    },
    /** 校验数据是否通过，并返回 **/
    formData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit('subFormData', {'valid': valid, 'data': this.form})
        } else {
          this.$emit('subFormData', {'valid': valid, 'data': null})
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      //禁用提交按钮
      this.isSubmitForm = true
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          if (this.enterType == 'Form') {
            /**
             * 业务表单处理
             */
            if (this.operType == 'edit') {
              update(this.tabGenId, this.prefixUrl, this.form).then(response => {
                this.msgSuccess('修改成功')
                this.$emit('cancel', {isRef: true})
              }).finally(() => {
                this.isSubmitForm = false
              })
            } else {
              add(this.tabGenId, this.prefixUrl, this.form).then(response => {
                this.msgSuccess('新增成功')
                this.$emit('cancel', {isRef: true})
              }).finally(() => {
                this.isSubmitForm = false
              })
            }
          } else {
            /**
             * 流程表单处理
             */
            //TODO 流程表单处理

          }
        } else {
          //解除禁用提交按钮
          this.isSubmitForm = false
        }
      })
    },

    /**-----------------old---------------------**/
    /**
     * 处理赋值
     * @param item
     */
    assignFormData(item) {

      if (item == null || item == undefined) {
        return
      }
      /**
       * 判断是否需要进行赋值到其他字段操作
       */
      if (item['isAssignOtherModel']) {
        var result = item.val
        if (item['assignType'] == 'append') {
          result = this.form[item.key] + item.val
        }
        //处理待赋值字段
        this.$set(this.form, item.key, result)

        for (var i = 0; i < this.formBuildConfig.length; i++) {
          if (item.key == this.formBuildConfig[i]['vModel']) {
            this.$set(this.formBuildConfig[i], 'defaultValue', result)
            break
          }
        }
      }
    },


  },
  watch: {
    form: {
      deep: true,
      handler() {
        this.init.fieldInfo.forEach((item, index) => {
          // 表单数据置空
          this.$set(this.init.fieldInfo[index], 'fieldData', this.form[item.columnName])
        })
      }
    }

  }
}
